package cn.johnyu.controller;

import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
public class AuthenticationController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @PostMapping("/login")
    public ResponseEntity<String> login(String username, String password, HttpSession session){
        UsernamePasswordAuthenticationToken token=new UsernamePasswordAuthenticationToken(username,password);
        try {
            log.info(username+" 登录成功!!");
            Authentication authenticated = authenticationManager.authenticate(token);
            User user = (User) authenticated.getPrincipal();
            //持久化用户认证的信息，并在CookieCheckFilter中使用
            session.setAttribute("user",user);
            return ResponseEntity.ok(user.getUsername()+" login success");
        } catch (AuthenticationException e) {
            //出现异常，说明认证失败
            log.info(username+" 登录失败!!");
            return  ResponseEntity.status(401).body(e.getMessage());
        }
    }
    @PostMapping("/logout")
    public String logout(HttpSession session){
        User user = (User)session.getAttribute("user");
        log.info(user.getUsername()+" 退出登录!!");
        session.removeAttribute("user");
        session.invalidate();
        return "logout success";
    }
}
